package edu.maplef.bookwild.logic.impl;

import java.util.ArrayList;
import java.util.List;

import com.xiaonei.api.XiaoneiRestClient;
import com.xiaonei.api.schema.Friend;
import com.xiaonei.api.schema.FriendsGetFriendsResponse;

import edu.maplef.bookwild.dao.IBuddyDao;
import edu.maplef.bookwild.logic.IBuddyLogic;
import edu.maplef.bookwild.schema.Buddy;

public class BuddyLogicImpl extends BaseLogicImpl implements IBuddyLogic {
	private IBuddyDao buddyDao;

	public void setBuddyDao(IBuddyDao buddyDao) {
		this.buddyDao = buddyDao;
	}

	public IBuddyDao getBuddyDao() {
		return buddyDao;
	}

	public List<Friend> getXnFriends(XiaoneiRestClient client) throws Exception {
		if (client == null)
			return null;
		client.friends_getFriends();
		FriendsGetFriendsResponse resp = (FriendsGetFriendsResponse) client
				.getResponsePOJO();
		List<Friend> friends = resp.getFriend();
		return friends;
	}

	@Override
	public List<Buddy> getMyBuddies(XiaoneiRestClient client) throws Exception {
		client.friends_getAppFriends();
		FriendsGetFriendsResponse resp = (FriendsGetFriendsResponse) client
				.getResponsePOJO();
		List<Friend> friends = resp.getFriend();
		List<Buddy> buddies = new ArrayList<Buddy>();
		for (Friend friend : friends) {
			try {
				int fid = friend.getId();
				Buddy b = buddyDao.getById(String.valueOf(fid));
				if (b != null)
					buddies.add(b);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
		return buddies;
	}

	public boolean isLogedIn(XiaoneiRestClient client) throws Exception {
		return false;
	}
}
